import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma.service';
import { UserAddDto } from 'src/types/dtoExt/User.dto';
import { UserInsertDto, UserInsertZod } from 'src/types/entrity/User.dto';
import { createCipheriv, createDecipheriv, scrypt, createHash } from 'crypto';
import { promisify } from 'util';
import { aesPsw } from 'src/config';

@Injectable()
export class UserService {
  constructor(
    private readonly mysql: PrismaService,
  ) {}

  async getUserByEmail(email: string) {
    return await this.mysql.user.findUnique({
      where: {
        email,
      },
    });
  }

  async getUserById(id: number) {
    return await this.mysql.user.findUnique({
      where: {
        id,
      },
      select: {
        psw: false
      }
    });
  }

  async insertUser(data: UserInsertDto) {
    return await this.mysql.user.create({
      data: UserInsertZod.parse(data),
    })
  }

  /** 
   * aes加密
   * @example $(UserService).aesEncode('lammu')
   */
  aesEncode(content: string) {
    const key = Buffer.from(aesPsw, 'utf8');
    const cipher = createCipheriv('aes-128-ecb', key, '');
    const encryptedText = Buffer.concat([
      cipher.update(content, 'utf-8'),
      cipher.final(),
    ]);
    return encryptedText.toString('base64');
  }


  /** 
   * aes解密
   * @example $(UserService).aesDecode('iVM/tnbnp6zsw8UOhV2+/g==')
   */
  aesDecode(content: string) {
    const key = Buffer.from(aesPsw, 'utf8');
    const decipher = createDecipheriv('aes-128-ecb', key, '');
    decipher.setAutoPadding(true);
    const decryptedText = Buffer.concat([
      decipher.update(content, 'base64'),
      decipher.final(),
    ]);
    return decryptedText.toString();
  }

  /**
   * 取文本hash
   * @example $(UserService).getHash('lammu')
   */
  getHash(content: string) {
    const hash = createHash('sha256');
    return hash.update(content).digest('hex');
  }
}
